package cn.ujn.medicalbackend.controller;

import cn.ujn.medicalbackend.common.BaseResponse;
import cn.ujn.medicalbackend.common.ErrorCode;
import cn.ujn.medicalbackend.common.ResultUtils;
import cn.ujn.medicalbackend.domain.Account;
import cn.ujn.medicalbackend.exception.BusinessException;
import cn.ujn.medicalbackend.request.AccountLoginRequest;
import cn.ujn.medicalbackend.service.AccountService;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import static cn.ujn.medicalbackend.constant.AccountConstant.ACCOUNT_LOGIN_STATE;

/**
 * @author XinCheng
 * date 2024-10-24
 */
@RestController
@RequestMapping("/account")
@CrossOrigin(origins = {"http://localhost:9092"})
public class AccountController {

    @Autowired
    private AccountService accountService;

    @PostMapping("/login")
    public BaseResponse<Account> accountLogin(@RequestBody AccountLoginRequest accountLoginRequest, HttpServletRequest request) {
        if (accountLoginRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        String uname = accountLoginRequest.getUname();
        String pwd = accountLoginRequest.getPwd();

        if (StringUtils.isAnyBlank(uname, pwd)) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "账号或密码为空");
        }
        Account account = accountService.accountLogin(uname, pwd, request);
        return ResultUtils.success(account);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        int result = accountService.userLogout(request);
        return ResultUtils.success(result);
    }

    @GetMapping("/current")
    public BaseResponse<Account> getCurrentUser(HttpServletRequest request) {
        Object accountObj = request.getSession().getAttribute(ACCOUNT_LOGIN_STATE);
        Account currentAccount = (Account) accountObj;
        if (currentAccount == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        long accountId = currentAccount.getId();
        // todo 校验用户是否合法
        Account account = accountService.getById(accountId);
        Account safetyAccount = accountService.getSafetyAccount(account);
        return ResultUtils.success(safetyAccount);
    }


}
